<template>
  <q-dialog class="my_dialog" v-model="isFlagShow">
    <q-card class="my-card q-mx-lg">
      <q-toolbar class="row items-center my_form_header">
        <div>
          {{dlgTitle}}
        </div>
        <q-space />
        <q-btn flat round dense icon="mdi-close" @click="close"/>
      </q-toolbar>
      <q-separator />
      <q-card-setion class="q-mx-sm">
        <q-scroll-area class="my-form-container">
          <div class="col q-gutter-xs">
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>公司名称：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  v-model="param.cname"
                  @blur="v$.cname.$touch()"
                  :error="v$.cname.$error"
                  error-message="请输入不少于2个字符！"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>公司类型：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="companyTypeArr"
                  v-model="param.type"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @blur="v$.type.$touch()"
                  :error="v$.type.$error"
                  error-message="请选择公司类型！"
                  />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>图标类型：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  clearable
                  :options="iconTypeArr"
                  v-model="iconType"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @update:model-value="refreshIconType(iconType)"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>公司图标：</q-item-label>
              <q-item-section>
                <AmyIconSelect
                  is-check="false"
                  :icon-arr="iconOptionArr"
                  :current-icon="param.icon"
                  :widthStyle="415"
                  @update="refreshIcon"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label>&nbsp;&nbsp;&nbsp;&nbsp;公司地址：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  v-model="param.address"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label>&nbsp;&nbsp;&nbsp;&nbsp;显示范围：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model="param.privilege"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label>&nbsp;&nbsp;&nbsp;&nbsp;排列序码：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  v-model="param.sortCode"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label>&nbsp;&nbsp;&nbsp;&nbsp;公司简介：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  type="textarea"
                  v-model="param.description"
                />
              </q-item-section>
            </q-item>
          </div>
        </q-scroll-area>
      </q-card-setion>
      <q-separator />
      <div class="q-gutter-sm my_form_footer">
        <q-btn
          unelevated
          dense
          label="提交"
          type="submit"
          color="teal-3"
          @click="onSubmit"
          style="width: 80px"
        />
        <q-btn
          unelevated
          dense
          label="重置"
          type="reset"
          color="orange-3"
          @click="onReset"
          style="width: 80px"
        />
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, ref, toRefs, PropType, watch, toRef } from 'vue';
import { isObjectEmpty } from '../../../util/utils';
import api from 'axios'
import { required, minLength } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core';
import { sysCatalogUrlAPI } from '../../../util/SysBaseConst';
import { cataItem } from '../../../hook/common/useCatalogType';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';

const AmyIconSelect = defineAsyncComponent(() => import('components/basic/AmyIconSelect.vue'));
import { CompanyItem, CompanyItemVO } from '../company/CompanyModel';

export default defineComponent({
  cname: 'CompanyDlg',
  components: {
    AmyIconSelect
  },
  props: {
    itemData: {
      type: Object as PropType<CompanyItem>,
      required: true
    },
    companyTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },
    iconTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    }
  },
  emits: ['submit-company-item', 'cancel-company-item'],
  setup (props, context) {
    //数据解构
    const {
      itemData,
      companyTypeArr,
      iconTypeArr
    } = toRefs(props);

    //*******************************
    //      目录操作
    //*******************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();

    //*******************************
    //      表单项
    //*******************************
    //窗口显示
    let isFlagShow = ref(false);

    //窗口标题
    let dlgTitle = ref('');

    //界面数据
    let param = ref<CompanyItemVO>({
      id: 0,
      cname: '',
      type: '',
      icon: '',
      address: '',
      privilege: 0,
      sortCode: '',
      description: '',
      parent: ''
    });

    //图标类型
    let iconType = ref('请选择图标类型');
    let iconOptionArr = ref<cataItem[]>([]);

    //关闭窗口
    const close = () => {
      isFlagShow.value = false;
      context.emit('cancel-company-item');
    }

    //显示窗口
    const show = (text: string) => {
      isFlagShow.value = true;
      dlgTitle.value = text;
    }

    //提交窗口
    const onSubmit = () => {
      v$.value.$validate();
      if (v$.value.$error) {
        alert('输入参数校验错误!');
      } else {
        isFlagShow.value = false;
        let item: CompanyItem = {
          id: param.value.id,
          cname: param.value.cname,
          typeId: findCatalogId(companyTypeArr.value, param.value.type),
          icon: param.value.icon,
          address: param.value.address,
          privilege: param.value.privilege,
          sortCode: param.value.sortCode,
          description: param.value.description,
          parentId: 0,
          createTime: '',
          createUserId: 0,
          updateTime: '',
          updateUserId: 0
        };

        //发送数据
        context.emit('submit-company-item', item);
      }
    }

    //重置
    const onReset = () => {
      if (param.value) {
        param.value.cname = '';
        param.value.type = '';
        param.value.icon = '';
        param.value.address = '';
        param.value.privilege = 0;
        param.value.sortCode = '';
        param.value.description = '';
        param.value.parent = '';
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //图标类型更新
    const refreshIconType = (sType: string) => {
      let index = (iconTypeArr.value).findIndex((item) => (item.label === sType));
      if ((iconTypeArr.value) && (index !== -1)) {
        param.value.icon = '';
        api.post(sysCatalogUrlAPI.ICON_SEARCH_LIST_API, {
          id: iconTypeArr.value[index].id
        }).then((res) => {
          if (res.data.message === 'Success') {
            let list: cataItem[] = res.data.data;
            iconOptionArr.value.length = 0;
            list.forEach((item) => {
              iconOptionArr.value.push(item);
            });
            console.log(list);
          }
        })
      }
    }

    //更新图标
    const refreshIcon = (icon: string) => {
      param.value.icon = icon;
    }
    //*******************************
    //      表单校验
    //*******************************
    //配置校验规则
    const rules = {
      id: {},
      cname: { required, minLength: minLength(2) },
      type: { required },
      icon: {},
      address: {},
      privilege: {},
      sortCode: {},
      description: {},
      parent: {}
    }

    //使用vuelidate，建立变量对应的校验规则
    const v$ = useVuelidate(rules, {
      id: toRef(param.value, 'id'),
      cname: toRef(param.value, 'cname'),
      type: toRef(param.value, 'type'),
      icon: toRef(param.value, 'icon'),
      address: toRef(param.value, 'address'),
      privilege: toRef(param.value, 'privilege'),
      sortCode: toRef(param.value, 'sortCode'),
      description: toRef(param.value, 'description'),
      parent: toRef(param.value, 'parent')
    });

    //*******************************
    //      启动模块
    //*******************************
    //初始化
    const init = () => {
      if (!isObjectEmpty(itemData.value)) {
        param.value.id = itemData.value.id;
        param.value.cname = itemData.value.cname;
        param.value.type = findCatalogLabel(companyTypeArr.value, itemData.value.typeId);
        param.value.icon = itemData.value.icon;
        param.value.address = itemData.value.address;
        param.value.privilege = itemData.value.privilege;
        param.value.sortCode = itemData.value.sortCode;
        param.value.description = itemData.value.description;
        param.value.parent = '';
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //监听对象的所有属性
    watch(() => itemData, () => {
      init();
    }, { deep: true });

    return {
      companyTypeArr,
      iconTypeArr,
      iconOptionArr,

      isFlagShow,
      dlgTitle,
      param,
      iconType,
      v$,
      init,
      close,
      show,
      onSubmit,
      onReset,
      refreshIcon,
      refreshIconType
    }
  }
})
</script>

<style lang="scss" scoped>
.my-card {
  alignment: center;
  width: 600px;
  max-width: 800px;

  .my-form-container {
    text-align: center;
    padding: 5px 50px 5px 50px;
    height: 430px;
  }
}
</style>
